<template>
  <view class="page-container">
    <scroll-view scroll-y class="form-scroll">
      <uni-forms ref="formRef" :modelValue="formData" :rules="rules" label-width="90px" label-align="right">
        <uni-card title="基本信息" :is-shadow="true">
          <uni-forms-item label="团购券名称" name="name" required>
            <uni-easyinput v-model="formData.name" placeholder="请输入团购券名称" />
          </uni-forms-item>
          <uni-forms-item label="状态" name="status" required>
            <uni-data-checkbox v-model="formData.status" :localdata="statusOptions"></uni-data-checkbox>
          </uni-forms-item>
        </uni-card>

        <uni-card title="价格与库存" :is-shadow="true">
          <uni-forms-item label="团购价(元)" name="price" required>
            <uni-easyinput v-model="formData.price" type="digit" placeholder="请输入团购价" />
          </uni-forms-item>
          <uni-forms-item label="原价(元)" name="original_price" required>
            <uni-easyinput v-model="formData.original_price" type="digit" placeholder="请输入原价" />
          </uni-forms-item>
          <uni-forms-item label="库存" name="stock" required>
            <uni-easyinput v-model="formData.stock" type="number" placeholder="请输入库存数量" />
          </uni-forms-item>
        </uni-card>

        <uni-card title="使用规则" :is-shadow="true">
          <uni-forms-item label="有效期" name="valid_range" required>
            <uni-datetime-picker type="daterange" v-model="formData.valid_range" />
          </uni-forms-item>
          <uni-forms-item label="适用范围" name="scope" required>
            <uni-data-select v-model="formData.scope" :localdata="scopeOptions"></uni-data-select>
          </uni-forms-item>
          <uni-forms-item v-if="formData.scope === CouponScope.Store" label="适用门店" name="store_ids">
            <uni-data-checkbox multiple v-model="formData.store_ids" :localdata="storeOptions"></uni-data-checkbox>
          </uni-forms-item>
          <uni-forms-item v-if="formData.scope === CouponScope.Venue" label="适用场地" name="venue_ids">
            <uni-data-checkbox multiple v-model="formData.venue_ids" :localdata="venueOptions"></uni-data-checkbox>
          </uni-forms-item>
        </uni-card>
      </uni-forms>
    </scroll-view>

    <view class="footer-actions safe-area-inset-bottom">
      <button class="submit-btn" @click="handleSubmit">提交</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { fetchGrouponDetail, createGroupon, updateGroupon } from '@/api/groupon';
import { fetchStores } from '@/api/store';
import { fetchVenues } from '@/api/store';
import { Groupon, CouponScope } from '@/types/groupon';
import moment from 'moment';

const formRef = ref<any>(null);
const formData = reactive<any>({
  name: '',
  status: 1,
  price: null,
  original_price: null,
  stock: 100,
  valid_range: [],
  scope: CouponScope.All,
  store_ids: [],
  venue_ids: [],
});

const rules = {
  name: { rules: [{ required: true, errorMessage: '请输入名称' }] },
  price: { rules: [{ required: true, errorMessage: '请输入团购价' }] },
  original_price: { rules: [{ required: true, errorMessage: '请输入原价' }] },
  stock: { rules: [{ required: true, errorMessage: '请输入库存' }] },
  valid_range: { rules: [{ required: true, errorMessage: '请选择有效期' }] },
  scope: { rules: [{ required: true, errorMessage: '请选择适用范围' }] },
};

const pageTitle = ref('新增团购券');
const grouponId = ref<number | null>(null);

const statusOptions = [ { value: 1, text: '启用' }, { value: 0, text: '禁用' }];
const scopeOptions = [
  { value: CouponScope.All, text: '全场通用' },
  { value: CouponScope.Store, text: '指定门店' },
  { value: CouponScope.Venue, text: '指定场地' },
];
const storeOptions = ref<{ value: number; text: string }[]>([]);
const venueOptions = ref<{ value: number; text: string }[]>([]);

const getRelatedData = async () => {
  try {
    const [storeRes, venueRes] = await Promise.all([fetchStores({}), fetchVenues({})]);
    storeOptions.value = storeRes.list.map(s => ({ value: s.id, text: s.name }));
    venueOptions.value = venueRes.list.map(v => ({ value: v.id, text: v.name }));
  } catch (error) {
    console.error('获取关联数据失败:', error);
  }
};

const handleSubmit = () => {
  formRef.value.validate().then(async (values: any) => {
    try {
      const dataToSubmit: Partial<Groupon> = {
        ...formData,
        price: Number(formData.price) * 100,
        original_price: Number(formData.original_price) * 100,
        stock: Number(formData.stock),
        valid_from: moment(formData.valid_range[0]).unix(),
        valid_to: moment(formData.valid_range[1]).unix(),
      };

      delete dataToSubmit.valid_range;

      if (grouponId.value) {
        await updateGroupon(grouponId.value, dataToSubmit as Groupon);
        uni.showToast({ title: '更新成功' });
      } else {
        await createGroupon(dataToSubmit as Groupon);
        uni.showToast({ title: '创建成功' });
      }
      setTimeout(() => uni.navigateBack(), 1500);
    } catch (error: any) {
      uni.showToast({ title: error.message || '操作失败', icon: 'none' });
    }
  });
};

const getGrouponDetail = async (id: number) => {
  try {
    const res = await fetchGrouponDetail(id);
    Object.assign(formData, res);
    
    formData.price = res.price / 100;
    formData.original_price = res.original_price / 100;
    formData.valid_range = [
      moment(res.valid_from * 1000).format('YYYY-MM-DD'),
      moment(res.valid_to * 1000).format('YYYY-MM-DD'),
    ];
  } catch (error) {
    console.error('获取团购券详情失败:', error);
  }
};

onLoad((options: any) => {
  getRelatedData();
  if (options.id) {
    grouponId.value = Number(options.id);
    pageTitle.value = '编辑团购券';
    uni.setNavigationBarTitle({ title: pageTitle.value });
    getGrouponDetail(grouponId.value);
  } else {
    uni.setNavigationBarTitle({ title: pageTitle.value });
  }
});
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--background-color);
}

.form-scroll {
  flex: 1;
  height: 0;
  padding-bottom: 80px;
}

.uni-card {
  margin: 10px !important;
}

.footer-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 10px 20px;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
}

.submit-btn {
  width: 100%;
  height: 44px;
  line-height: 44px;
  background-color: var(--primary-color);
  color: #fff;
  border-radius: var(--border-radius);
  font-size: 16px;
}
</style>